package com.hxci.service;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.utils.Constants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

@Service
public class AiAssistantService {

    @Value("${dashscope.api.key:}")
    private String apiKey;

    @PostConstruct
    public void init() {
        String envKey = System.getenv("DASHSCOPE_API_KEY");
        if (apiKey != null && !apiKey.isEmpty()) {
            Constants.apiKey = apiKey;
        } else if (envKey != null && !envKey.isEmpty()) {
            Constants.apiKey = envKey;
        }
    }

    public String getAnswer(String question) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message userMessage = Message.builder().role(Role.USER.getValue()).content(question).build();
        GenerationParam param = GenerationParam.builder().model("qwen-turbo").messages(Arrays.asList(userMessage)).resultFormat(GenerationParam.ResultFormat.MESSAGE).build();
        GenerationResult result = gen.call(param);
        return result.getOutput().getChoices().get(0).getMessage().getContent();
    }

    public String getAnswer(List<Message> history) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        GenerationParam param = GenerationParam.builder().model("qwen-turbo").messages(history).resultFormat(GenerationParam.ResultFormat.MESSAGE).build();
        GenerationResult result = gen.call(param);
        return result.getOutput().getChoices().get(0).getMessage().getContent();
    }

}
